package org.noote.libs.widget;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

public class WidgetTexturePack {

	int[] textureIDs = null;
	
	public boolean create(GL10 gl, int iTextures)
	{
		textureIDs=new int[iTextures];
		
		gl.glGenTextures(textureIDs.length, textureIDs, 0);
		
		return true;
	}
	
	public int getTextureID(int idx)
	{
		if(textureIDs == null || idx<0) return -1;
		if(textureIDs != null && idx>textureIDs.length) return -1;
		
		return textureIDs[idx];
	}
	
	public boolean loadImageFromResource(Context ctx, int idRessource,
			GL10 gl, int idx)
	{
		int textureID = getTextureID(idx);
		if(textureID == -1) return false;
		return _loadImageFromResource(ctx, idRessource, gl, textureID);
	}
	
	static protected boolean _loadImageFromResource(Context ctx, int idRessource,
			GL10 gl, int textureID) {
		
		InputStream istream=null;
		Bitmap bitmap=null;
		try {
			istream = ctx.getResources().openRawResource(idRessource);
			bitmap = BitmapFactory.decodeStream(istream);
		} finally {
			try {
				if(istream != null)
					istream.close();
			} catch (IOException e) {
				return false;
			}
		}

		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);

		// setup filters for texture
		gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR );  // Set Minification Filter
		gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR );  // Set Magnification Filter
		gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE );  // Set U Wrapping
		gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE );  // Set V Wrapping

      	// load the generated bitmap onto the texture
		if(gl instanceof GL11)
			gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL11.GL_GENERATE_MIPMAP, GL10.GL_TRUE);
		
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
      	gl.glBindTexture( GL10.GL_TEXTURE_2D, 0 );      // Unbind Texture
		bitmap.recycle();
		
		return true;
	}
}
